package com.amado.course42Nio.charSystem;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author wangyulong
 * @version 1.5.0
 * @date 2020/3/8 20:41
 */
public class CharClient {
    Selector selector;
    String name="";
    SocketChannel socketChannel;

    public static void main(String[] args) throws IOException {
        new CharClient().go();
    }

    public CharClient() throws IOException {
        selector = Selector.open();
        socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 4444));
        //容易忘记
        socketChannel.configureBlocking(false);
        socketChannel.register(selector,SelectionKey.OP_READ);
        while(!socketChannel.finishConnect()){

        }
        System.out.println("建立链接成功");
    }

    public void go() throws IOException {
        new Thread(()->{
            try {
                System.out.println("---");
                while (true) {
                    int selectCount = selector.select();
                    if(selectCount==0){
                        continue;
                    }
                    System.out.println("===========");
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey selectionKey = iterator.next();
                        //容易忘记
                        iterator.remove();
                        if (selectionKey.isReadable()) {
                            read(selectionKey);
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("out");
        }).start();

        Scanner scan = new Scanner(System.in);
        while(true){
            String input = scan.nextLine();
            if(name.equals("")){
                ByteBuffer wrap = ByteBuffer.wrap((CommandEnum.SET_NAME.getCommand() + "##" + input+"##null").getBytes());
                socketChannel.write(wrap);
            }else{
                ByteBuffer wrap = ByteBuffer.wrap((CommandEnum.CHARS.getCommand() + "##" + name+"##"+input).getBytes());
                socketChannel.write(wrap);
            }
        }
    }

    private void read(SelectionKey selectionKey) throws IOException {
        SocketChannel channel = (SocketChannel) selectionKey.channel();
        ByteBuffer readBuffer = ByteBuffer.allocate(1024);
        channel.read(readBuffer);
        readBuffer.flip();
        CharBuffer charBuffer = Charset.forName("UTF-8").decode(readBuffer);
        String content = new String(charBuffer.array());
        if(CommandEnum.NAME_OK.getCommand().equals(getCommand(content))){
            name = getName(content);
            System.out.println("name 设置成功");
            //nothing
        }else if(CommandEnum.CHARS.getCommand().equals(getCommand(content))){
            readContent(content);
        }else if(CommandEnum.SET_NAME.getCommand().equals(getCommand(content))||CommandEnum.NAME_EXISTS.getCommand().equals(getCommand(content))){
            pring(content);
        }
    }

    private void pring(String cotent) throws IOException {
        System.out.println(getContent(cotent));
    }
    private void readContent(String cotent) throws IOException {
        System.out.println(getName(cotent)+"说:"+getContent(cotent));
    }
    private String getCommand(String content){
        String contentArray[]  = content.split("##");
        return contentArray[0];
    }
    private String getName(String content){
        String contentArray[]  = content.split("##");
        return contentArray[1];
    }
    private String getContent(String content){
        String contentArray[]  = content.split("##");
        return contentArray[2];
    }

}
